import type { LoginResponseType } from './types';
import { useState } from 'react'
import useRequest from '../../hooks/useRequest'
import { useNavigate } from 'react-router-dom';
import { message } from '../../utils/message';

const Login = () => {
  const [phoneNumber, setPhoneNumber] = useState('')
  const [password, setPassword] = useState('')
  const navigate = useNavigate();
  const { request } = useRequest<LoginResponseType>({ manual: true })
  const handleSubmit = () => {
    if (!phoneNumber) {
      message('手机号码不得为空！');
      return;
    }
    if (!password) {
      message('密码不得为空！');
      return;
    }
    request({
      url: '/login.json',
      method: 'POST',
      data: {
        phone: phoneNumber,
        password: password,
      }
    }).then((data) => {
      const { data: { token } } = data;
      console.log(token)
      if (token) {
        localStorage.setItem('token', token);
        navigate('/home');
      }
    }).catch((e: any) => {
      message(e?.message || '未知异常')
    });
  }

  return (
    <>
      <div className="form">
        <div className="form-item">
          <div className="form-item-title">手机号</div>
          <input
            className="form-item-content"
            value={phoneNumber}
            placeholder="请输入手机号码"
            onChange={(e) => { setPhoneNumber(e.target.value) }}
          />
        </div>
        <div className="form-item">
          <div className="form-item-title">密码</div>
          <input
            type="password"
            className="form-item-content"
            value={password}
            placeholder="请输入密码"
            onChange={(e) => { setPassword(e.target.value) }}
          />
        </div>
      </div>
      <div className="submit" onClick={handleSubmit} >
        登录
      </div>
      <p className="notice">
        *登录即表示您赞同使用条款及隐私政策
      </p>
    </>
  )
}

export default Login